import Taro, { Component } from '@tarojs/taro';
import { connect } from '@tarojs/redux';
import { Canvas, View, Image, Text } from '@tarojs/components';
import { AtButton } from 'taro-ui';
import './styles.less';

function getTouchPos(e) {
  const rect = {
    left: 70,
    top: 40
  };

  // 小程序下有e.changedTouches[0].x，没有e.changedTouches[0].clientX
  // h5下有e.changedTouches[0].clientX，没有e.changedTouches[0].x
  // 因此需要做兼容
  const touch = e.changedTouches[0];
  return {
    x: +(touch.clientX || touch.x) - rect.left,
    y: +(touch.clientY || touch.y) - rect.top
  };
}

let ctx = {};
// 画笔的颜色
const BLACK = '#000';
let canvasw = 0;
let canvash = 0;
// 不用state，否则会在小程序下造成性能问题
const initialCoord = {
  x: 0,
  y: 0
};
let drawing = false;
let mousePos = initialCoord; // 当前手的位置
let lastPos = initialCoord; // 上一帧手的位置
let screen = {};

function draw() {
  if (drawing) {
    ctx.moveTo(lastPos.x, lastPos.y);
    ctx.lineTo(mousePos.x, mousePos.y);
    // drawLineNoAliasing(ctx, lastPos.x, lastPos.y, mousePos.x, mousePos.y);
    ctx.stroke();
    ctx.draw(process.env.TARO_ENV === 'weapp' ? true : false);
    lastPos = mousePos;
  }
}

class Draw extends Component {
  constructor(props) {
    super();

    this.canvasRef = (ref) => {
      this.refDom = ref;
    };

    this.state = {
      color: BLACK, // 画笔的颜色
      orderId: props.orderId,
      btnLoading: false
      // orgId: null
    };

    this.config = {
      allowsBounceVertical: 'NO', // 防止滚动
      disableScroll: true // 防止滚动
      // pageOrientation: "landscape" // 横屏
    };

    // 防止滚动
    /*document &&
      document.body.addEventListener("touchmove", e => e.preventDefault(), {
        passive: false
      });*/

    console.log(document.body.style);

    this.handleTouchStart = this.handleTouchStart.bind(this);
    this.handleTouchEnd = this.handleTouchEnd.bind(this);
    this.handleMove = this.handleMove.bind(this);
    this.setupCanvasContext = this.setupCanvasContext.bind(this);
    this.clearCanvas = this.clearCanvas.bind(this);
  }
  componentDidMount() {
    // 创建上下文
    ctx = Taro.createCanvasContext('ctx', this);
    // 设置上下文
    this.setupCanvasContext(BLACK);
    // 开启新路径（用于clear）
    ctx.beginPath();
    this.getCanvasSize();

    // 每隔1000 / 60 ms draw一次
    // this.interval = setInterval(draw, 34);

    const canvas_dom = document.getElementById('ctx');
    canvas_dom.addEventListener('touchstart', function (event) {
      event.preventDefault();
    });
    canvas_dom.addEventListener('touchmove', function (event) {
      event.preventDefault();
    });
    canvas_dom.addEventListener('touchend', function (event) {
      event.preventDefault();
    });
    canvas_dom.addEventListener('touchcancel', function (event) {
      event.preventDefault();
    });
    console.log(canvas_dom);
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }
  setupCanvasContext(color) {
    const res = Taro.getSystemInfoSync();
    const pixelRatio = res.pixelRatio;
    screen = {
      width: res.windowWidth,
      height: res.windowHeight
    };
    const lineWidth =
      process.env.TARO_ENV === 'h5' ? pixelRatio * 1.5 : Taro.pxTransform(5).slice(0, -3);
    ctx.setLineWidth(lineWidth);
    ctx.setStrokeStyle(color);
    ctx.setLineJoin('round');
    ctx.setLineCap('round');
  }
  interval;
  handleTouchStart(e) {
    drawing = true;
    lastPos = mousePos = getTouchPos(e);
  }
  handleTouchEnd() {
    drawing = false;
  }
  handleMove(e) {
    mousePos = getTouchPos(e);
    if (mousePos.y > screen.height) {
      drawing = false;
    }
    draw();
  }

  // 获取 canvas 的尺寸（宽高）
  getCanvasSize() {
    const query = Taro.createSelectorQuery();
    query.select('#ctx').boundingClientRect(function (res) {
      document.getElementById('ctx').width = res.width;
      document.getElementById('ctx').height = res.height;
      canvasw = res.width;
      canvash = res.height;
    });
    query.exec();
  }

  clearCanvas() {
    ctx.closePath();
    ctx.clearRect(0, 0, 9999, 9999);
    ctx.draw();
    ctx.beginPath();
    this.setupCanvasContext(this.state.color);
  }
  save = async () => {
    this.setState({ ...this.state, btnLoading: true });
    // 是否画过，如果压根没有画，点击确定则不需要保存
    const r = await Taro.canvasGetImageData({
      canvasId: 'ctx',
      x: 0,
      y: 0,
      width: screen.width,
      height: screen.height
    });
    const matrix = process.env.TARO_ENV === 'h5' ? r.data.data : r.data;

    /* if (matrix.every(b => b === 0)) {
      Taro.showToast({
        title: "签名内容不能为空！",
        icon: "none"
      });
      this.setState({ ...this.setState, btnLoading: false });
      return false;
    } */

    let that = this;
    Taro.showLoading({
      title: '加载中',
      mask: true
    });
    // 生成图片
    Taro.canvasToTempFilePath({
      canvasId: 'ctx',
      fileType: 'png',
      success: (res) => {
        const { dispatch } = this.props;

        // 图片base64
        const base64 = res.tempFilePath.replace('data:image/png;base64,', '')

        /* TODO: 处理签名完成后的逻辑 */
      },
      fail(err) {
        console.log(err);
        Taro.hideLoading();
      }
    });

    // 啥也没画
  };
  changePenColor(color) {
    this.setState({
      color
    });
    this.setupCanvasContext(color);
  }

  renderCanvas = () => {
    return (
      <View className="canvas-h5-wrap">
        <View className="text-wrap">
          <Text className="text">签</Text>
          <Text className="text">署</Text>
          <Text className="text">区</Text>
        </View>
        <Canvas
          onTouchMove={this.handleMove}
          onTouchStart={this.handleTouchStart}
          onTouchEnd={this.handleTouchEnd}
          canvasId="ctx"
          id="ctx"
          style="width: calc(100vw - 91px); height:calc(100vh - 80px)"
          // width={canvasw}
          // height={canvash}
          className="ctx"
          disableScroll
        ></Canvas>
      </View>
    );
  };
  render() {
    return (
      <View className="draw-wrapper">
        <View className="canvas-wrap" id="canvasRef" ref={this.canvasRef}>
          {this.renderCanvas()}
        </View>
        <View className="btn-wrap" onTouchStart={this.handleTouchEnd}>
          <View className="btns" onClick={(e) => e.stopPropagation()}>
            <AtButton
              circle
              className="my-Button clear"
              // size="small"
              customStyle={{
                width: '105px',
                height: '45px',
                display: 'flex',
                alignItems: 'center',
                background: 'rgba(0, 0, 0, 0.06)',
                fontSize: '14px',
                color: 'rgba(36, 29, 4, 1)',
                border: 'none'
              }}
              onClick={this.clearCanvas}
            >
              重写
            </AtButton>
            <AtButton
              type="primary"
              className="my-Button submit"
              circle
              // size="small"
              customStyle={{
                width: '105px',
                height: '45px',
                display: 'flex',
                alignItems: 'center',
                background: '#7be1ce',
                boxShadow: `0px 3px 6px 0px #7be1ce`,
                fontSize: '14px',
                border: 'unset'
              }}
              loading={this.state.btnLoading}
              disabled={this.state.btnLoading}
              onClick={this.save}
            >
              完成
            </AtButton>
          </View>
        </View>
      </View>
    );
  }
}

export default connect(({ order }) => ({ ...order }))(Draw);
